package com.kob.backend.service.impl.ranklist;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kob.backend.mapper.BotMapper;
import com.kob.backend.mapper.RecordMapper;
import com.kob.backend.mapper.UserMapper;
import com.kob.backend.pojo.Bot;
import com.kob.backend.pojo.Record;
import com.kob.backend.pojo.User;
import com.kob.backend.service.ranklist.RankListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

@Service
public class RankListServiceImpl implements RankListService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BotMapper botMapper;

    @Autowired
    private RecordMapper recordMapper;

    @Override
    public JSONObject getRankList(Integer page) {
        IPage<User> userPage = new Page<>(page,6);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("rating");
        List<User> users = userMapper.selectPage(userPage, queryWrapper).getRecords();
        JSONObject resp = new JSONObject();
        for (User user : users)
            user.setPassword(""); //返回清空密码，防止密码泄露
        HashMap<Integer, Long> botMap = new HashMap<>();
        HashMap<Integer, Long> userRecord = new HashMap<>();
        for (User user : users) {
            QueryWrapper<Bot> botQueryWrapper = new QueryWrapper<>();
            botQueryWrapper.eq("user_id",user.getId());
            botMap.put(user.getId(),botMapper.selectCount(botQueryWrapper));

            QueryWrapper<Record> recordQueryWrapper = new QueryWrapper<>();
            recordQueryWrapper.eq("a_id",user.getId()).or().eq("b_id",user.getId());
            userRecord.put(user.getId(),recordMapper.selectCount(recordQueryWrapper));
        }
        resp.put("user_bot",botMap);
        resp.put("user_record",userRecord);
        resp.put("users",users);
        resp.put("users_count",userMapper.selectCount(null));
        return resp;
    }
}
